from qiniu import Auth
from django.utils.decorators import method_decorator
import jwt
from django.http import HttpResponse
from django.shortcuts import render
from rest_framework.views import APIView
from rest_framework.response import Response


# Create your views here.

#装饰器的使用
from myapp.models import User,KaoGoods
from myapp.myser import UserSer, KaoGoodsSer

import pymongo

# 建立mongo连接对象
mongo_client = pymongo.MongoClient(host="localhost", port=27017)


#商品列表页
class GoodsList1(APIView):

	def get(self, request):
		#当前页
		page = int(request.GET.get("page", 1))
		#一页有多少条商品
		size = int(request.GET.get("size", 1))

		#定义从哪儿开始切
		data_start = (page-1) * size

		#定义切到哪儿
		data_end = page * size

		#查询数据
		goodslist = KaoGoods.objects.all()[data_start:data_end]

		#查询总数量
		count = KaoGoods.objects.count()

		#序列化操作
		goods_ser = KaoGoodsSer(goodslist, many=True)

		res = {}
		res['total'] = count
		res['data'] = goods_ser.data
		return Response(res)



# 商品标签添加接口
class InsertTags1(APIView):
	def get(self, request):

		id = request.GET.get('id', None)
		tags = request.GET.get('tags', None)

		# 字符串转列表
		tags = tags.split(",")

		# 列表转字符串
		# tags = ",".join(tags)
		# print(tags)

		# 建立数据库对象
		db = mongo_client.md
		# 建立表对象
		table = db.mytag

		# 排重操作
		# 查询
		res = table.find({"gid": str(id)}).count()
		if res > 0:
			return Response({'message': '重复数据'})
		else:
			# 入库
			table.insert({'gid': str(id), 'tags': tags})
			return Response({'message': '入库成功'})


# 添加商品
class InsertGoods1(APIView):

	def get(self, request):

		#接收参数  dict['username']
		name = request.GET.get('name', 'null')

		#排重
		goods = KaoGoods.objects.filter(name=name).first()

		if goods:
			res = {}
			res['code'] = 405
			res['message'] = '该商品已存在'
			return Response(res)

		#入库
		goods = KaoGoods(name=name,)
		goods.save()

		#查询商品id
		goods = KaoGoods.objects.filter(name=name).first()

		res = {}
		res['code'] = 200
		res['id'] = goods.id
		res['message'] = '恭喜，添加成功'

		return Response(res)




def my_decorator(func):
    def warpper(request, *args, **kwargs):
        #判断JWT逻辑
        uid = request.GET.get("uid")
        client_jwt = request.GET.get("jwt1", 'null')
        # 查询用户库中存储的上传的视频
        user = User.objects.filter(id=int(uid)).first()
        try:
            decode_jwt = jwt.decode(client_jwt, '0722', algorithms=['HS256'])
            #进行jwt解密，如果jwt中存的视频与用户库中存储的不一致，说明播放视频并非用户上传视频
            if str(decode_jwt['img']) != user.img:
                return HttpResponse("非法视频")
        except Exception as e:
            return HttpResponse("非法视频！")

        return func(request, *args, **kwargs)
    return warpper


#类装饰器调用


#定义七牛云存储接口
class Qiniu_kaos(APIView):

    def get(self, request):
        #定义密钥
        q = Auth('5Veq6sNOg8ka1d9uIeOS3Wazb7AESwvrBbCsdJWi',
                 '_8g1em1f0XJ-Ge4AoxZhNSc3p1HnqvhqFuC6UNcJ')
        #指定上传空间mdmd2020
        token = q.upload_token('mdmd2020')
        print(token)
        res = {}
        res['token'] = token
        #只给前端返回一个token
        return Response(res)

#更新用户数据
class UpdateUser(APIView):
    def get(self, request):
        img = request.GET.get("img")
        uid = request.GET.get("uid")
        #查询数据
        user = User.objects.get(id=int(uid))
        #更新时将用户上传的视频进行JWT加密
        encode_jwt = jwt.encode({'img': str(img)}, '0722', algorithm='HS256')
        encode_str = str(encode_jwt, 'utf-8')

        user.img = img
        user.save()

        return Response({'code': 200, 'message': '更新成功', 'jwt': encode_str})


#用户信息类
class UserInfo1(APIView):
    @method_decorator(my_decorator)
    def get(self, request):
        uid = request.GET.get('uid')
        user = User.objects.get(id=int(uid))
        user_ser = UserSer(user).data
        print(user_ser)
        return Response(user_ser)
